// 
// Entify project
//  
// Author:
//       Lauri Taimila <lauri@taimila.com>
// 
// Copyright (c) 2010 Lauri Taimila
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.IO;
using MonoDevelop.Core;
using MonoDevelop.Core.Serialization;
using MonoDevelop.Ide;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Projects;

namespace MonoDevelop.EntifyEditor
{
	/// <summary>
	/// Entify editor view. Implements visual designer for entify framework.
	/// </summary>
	public class EntifyEditorView : AbstractViewContent
	{
		/// <summary>
		/// In-memory representation of the entity set. This is used
		/// as a model for UI. Model is serialized to XML when saved
		/// to disk.
		/// </summary>
		private EntitySet model;

		/// <summary>
		/// File that contains the current model.
		/// </summary>
		private string filename;

		/// <summary>
		/// Creates an new EntifyEditorView instance.
		/// </summary>
		public EntifyEditorView()
		{
			this.IsViewOnly = false;
		}

		/// <summary>
		/// Gets the icon for entify editor.
		/// </summary>
		public override string StockIconId
		{
			get
			{
				return "md-entityset-file-icon-small";
			}
		}

		/// <summary>
		/// Gets the entify editor's root widget.
		/// </summary>
		public override Gtk.Widget Control
		{
			get
			{
				EntifyEditorWidget widget = new EntifyEditorWidget(this.model);
				widget.ModelChanged += delegate { this.IsDirty = true; };
				widget.Visible = true;
				return widget;
			}
		}

		/// <summary>
		/// Gets the label for editor's tab.
		/// </summary>
		public override string TabPageLabel
		{
			get
			{
				return "Entities";
			}
		}

		/// <summary>
		/// Loads entity set from file. Deserializes XML presentation to model objects.
		/// </summary>
		/// <param name="fileName">
		/// A <see cref="System.String"/>
		/// </param>
		public override void Load(string fileName)
		{
			XmlDataSerializer serializer = new XmlDataSerializer (new DataContext ());
			this.model = (EntitySet) serializer.Deserialize (fileName, typeof(EntitySet));

			if(this.model.Namespace.Trim() == string.Empty)
			{
				this.model.Namespace = (this.Project as DotNetProject).DefaultNamespace;
			}
			
			this.ContentName = fileName;
			this.filename = fileName;
		}

		/// <summary>
		/// Save current model to file in XML format and generates C# classes for entities.
		/// </summary>
		public override void Save()
		{
			if(this.model.IsValid)
			{
				XmlDataSerializer serializer = new XmlDataSerializer(new DataContext());
				serializer.Serialize(this.filename, this.model);
				this.SaveGeneratedCode(Path.GetDirectoryName(this.filename));
				this.GeneratePartialClasses(Path.GetDirectoryName(this.filename));
				this.IsDirty = false;
			}
			else
			{
				MessageService.ShowWarning("Unable to save entity set!",
				                         "Entity set is not valid and cannot be saved. Please check that " +
				                         "all entity, property and relation names are valid. " +
				                         "All these names must be valid C# identifier names, so for example " +
				                         "no spaces in names are allowed. Relation names must start with uppercase letter.\n\n" +
				                         "Also make sure that validation rules make sense. E.g. minumum value " +
				                         "is not larger than maximum value.\n\n" +
				                         "Entity set cannot be saved until it's fixed.");
			}
		}

		/// <summary>
		/// Save current model to file in XML format and generates C# classes for entities.
		/// </summary>
		/// <param name="fileName">
		/// Output filename. <see cref="System.String"/>
		/// </param>
		public override void Save(string fileName)
		{
			if(this.model.IsValid)
			{
				XmlDataSerializer serializer = new XmlDataSerializer(new DataContext());
				serializer.Serialize(fileName, this.model);
				this.SaveGeneratedCode(Path.GetDirectoryName(fileName));
				this.GeneratePartialClasses(Path.GetDirectoryName(fileName));
				this.IsDirty = false;
			}
			else
			{
				MessageService.ShowWarning("Unable to save entity set!",
				                         "Entity set is not valid and cannot be saved. Please check that " +
				                         "all entity, property and relation names are valid. " +
				                         "All these names must be valid C# identifier names, so for example " +
				                         "no spaces in names are allowed. Relation names must start with uppercase letter.\n\n" +
				                         "Also make sure that validation rules make sense. E.g. minumum value " +
				                         "is not larger than maximum value.\n\n" +
				                         "Entity set cannot be saved until it's fixed.");
			}
		}
		
		/// <summary>
		/// Generates partial stub classes for entities. File is only created
		/// if it doesn't exists already! Existing files are never removed.
		/// </summary>
		private void GeneratePartialClasses(string outputFolder)
		{
			if(this.model.GeneratePartialClasses)
			{
				EntityCodeGenerator generator = new EntityCodeGenerator(this.model);

				foreach(Entity entity in this.model.Entities)
				{
					string generatedCode = generator.GetPartialClassForEntity(entity);
					string stubFilename = Path.Combine(outputFolder, entity.Name + ".cs");

					try
					{
						if(!File.Exists(stubFilename))
						{
							StreamWriter writer = File.CreateText(stubFilename);
							writer.Write(generatedCode);
							writer.Flush();
							writer.Close();

							ProjectFile projectFile = new ProjectFile(stubFilename);
							projectFile.DependsOn = this.filename;
							projectFile.Visible = true;
							this.Project.AddFile(projectFile);
						}
					}
					catch(Exception e)
					{
						LoggingService.LogError("Entify add-in was unable to save partial class for entity type '" +
						                        entity.Name + "' to file: " + stubFilename + "\n" + e.Message);
						//TODO: Show error dialog.
					}
				}
				
				//TODO: How to implement this with latest MonoDevelop?
				//IdeApp.ProjectOperations.Save(this.Project);
			}
		}

		/// <summary>
		/// Write generated C# entity classes to specified file.
		/// </summary>
		/// <param name="filename">
		/// Filename of the model XML. <see cref="System.String"/>
		/// </param>
		private void SaveGeneratedCode(string outputFolder)
		{
			string codeFilename = Path.Combine(outputFolder, this.model.FilenameForGeneratedClasses);

			EntityCodeGenerator generator = new EntityCodeGenerator(this.model);
			string generatedCode = generator.GetEntityClasses();

			try
			{
				if (File.Exists(codeFilename))
				{
					File.Delete(codeFilename);
				}

				StreamWriter writer = File.CreateText(codeFilename);
				writer.Write(generatedCode);
				writer.Flush();
				writer.Close();
			}
			catch(Exception e)
			{
				LoggingService.LogError("Entify add-in was unable to save generated code to file: " + codeFilename + "\n" + e.Message);
				//TODO: Show error dialog.
			}

			ProjectFile projectFile = new ProjectFile(codeFilename);
			projectFile.DependsOn = this.filename;
			projectFile.Visible = false;

			try
			{
				this.Project.Files.Remove(codeFilename);
			}
			catch {}

			this.Project.AddFile(projectFile);
		}

		/// <summary>
		/// Dispose view. This method is called when the tab is closed by user.
		/// </summary>
		public override void Dispose()
		{
		}
	}
}
